﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Globalization;
using System.Configuration;

namespace Clinica_Frba
{
    public partial class FormBuscarTurno : Form
    {
        string strIDProfesional;
        string strIDAfiliado;
        string strIDAgendaProfesionalDelTurno;

        public FormBuscarTurno(string IDAfiliado, string IDProfesional)
        {
            InitializeComponent();

            mcFechaAElegir.MinDate = DateTime.Parse(ConfigurationManager.AppSettings["fechainicio"]);

            strIDAfiliado = IDAfiliado;
            strIDProfesional = IDProfesional;
            strIDAgendaProfesionalDelTurno = "NULL";



            SqlConnection myConnection = new SqlConnection(publico.ConnectionString);
            myConnection.Open();

            string strQuery = "SELECT Dia, HORA_INICIO, HORA_FIN FROM AGENDA_PROF WHERE ID_PROF = '" + strIDProfesional + "'";
            SqlCommand consulta = new SqlCommand(strQuery, myConnection);
            SqlDataReader executeCMD = consulta.ExecuteReader();

            while (executeCMD.Read())
            {
                string dia = executeCMD["Dia"].ToString();

                switch (dia)
                {
                    case "Lunes": lLunes.Text += ( executeCMD["HORA_INICIO"].ToString() + " - " + executeCMD["HORA_FIN"].ToString());
                        break;
                    case "Martes": lMartes.Text += (executeCMD["HORA_INICIO"].ToString() + " - " + executeCMD["HORA_FIN"].ToString());
                        break;
                    case "Miercoles": lMiercoles.Text += (executeCMD["HORA_INICIO"].ToString() + " - " + executeCMD["HORA_FIN"].ToString());
                        break;
                    case "Jueves": lJueves.Text += (executeCMD["HORA_INICIO"].ToString() + " - " + executeCMD["HORA_FIN"].ToString());
                        break;
                    case "Viernes": lViernes.Text += (executeCMD["HORA_INICIO"].ToString() + " - " + executeCMD["HORA_FIN"].ToString());
                        break;
                    case "Sabado": lSabado.Text += (executeCMD["HORA_INICIO"].ToString() + " - " + executeCMD["HORA_FIN"].ToString());
                        break;
                    default:
                        break;
                }


            }

        }

        private string ParsearDiaAEspaniol(string dia)
        {
            switch(dia)
            {
                case "Sunday" : return "Domingo";
                case "Monday": return "Lunes";
                case "Tuesday": return "Martes";
                case "Wednesday": return "Miercoles";
                case "Thursday": return "Jueves";
                case "Friday": return "Viernes";
                case "Saturday": return "Sabado";
                default: return "ERROR";
            }

        }

        private void bElegirFecha_Click(object sender, EventArgs e)
        {

            dgvElegirHorario.Rows.Clear();
            string fecha = mcFechaAElegir.SelectionRange.Start.ToString("yyyy-MM-dd");

            DayOfWeek diaDeLaSemana = mcFechaAElegir.SelectionRange.Start.DayOfWeek;
            string diaEnEspaniol = ParsearDiaAEspaniol(diaDeLaSemana.ToString());

            SqlConnection myConnection = new SqlConnection(publico.ConnectionString);
            myConnection.Open();

            string strQuery = "SELECT ap.HORA_INICIO, ap.HORA_FIN, ap.ID_AGENDA_P FROM AGENDA_PROF ap WHERE ID_PROF ='" + strIDProfesional + "'AND ap.Dia ='" + diaEnEspaniol + "'";
            SqlCommand consulta = new SqlCommand(strQuery, myConnection);
            SqlDataReader executeCMD = consulta.ExecuteReader();


            DateTime dtPrimerTurno;
            DateTime dtUltimoTurno;

            if (executeCMD.HasRows)
            {
                executeCMD.Read();
                dtPrimerTurno = DateTime.Parse(fecha +" "+ executeCMD["HORA_INICIO"].ToString());
                dtUltimoTurno = DateTime.Parse(fecha +" "+ executeCMD["HORA_FIN"].ToString());
            }
            else
            {
                return;
            }

            strIDAgendaProfesionalDelTurno = executeCMD["ID_AGENDA_P"].ToString();
            executeCMD.Close();
            strQuery = "SELECT tu.Fecha , tu.Estado FROM TURNO tu JOIN AGENDA_PROF ap ON ap.ID_PROF = tu.ID_PROF WHERE tu.ID_PROF = '" + strIDProfesional + "' AND CONVERT(TIME,tu.Fecha) >= ap.HORA_INICIO AND CONVERT(TIME, tu.fecha) <= ap.HORA_FIN AND ap.Dia = '" + diaEnEspaniol + "' AND  CONVERT(date, tu.fecha) = CONVERT( date, '" + fecha + "' ) AND tu.ESTADO = 'T' ORDER BY tu.FECHA";
            consulta = new SqlCommand(strQuery, myConnection);
            executeCMD = consulta.ExecuteReader();


            bool bHayMasTurnos;

            if (executeCMD.HasRows)
                bHayMasTurnos = true;
            else
                bHayMasTurnos = false;

            DateTime dtTurnoLibre = dtPrimerTurno;
            executeCMD.Read();
            while (dtTurnoLibre < dtUltimoTurno)
            {
                if (!bHayMasTurnos || dtTurnoLibre.ToString() != executeCMD["Fecha"].ToString())
                {
                    dgvElegirHorario.Rows.Add(dtTurnoLibre.ToString(), "Disponible");
                }
                else
                {
                    bHayMasTurnos = executeCMD.Read();
                }
                dtTurnoLibre = dtTurnoLibre.AddMinutes(30);
            }
            
        }

        private void dgvElegirHorario_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dgvElegirHorario.Columns["Seleccionar"].Index)
            {
                if (e.RowIndex >= 0)
                {
                    DateTime dtFecha = DateTime.Parse(dgvElegirHorario.Rows[e.RowIndex].Cells["Fecha"].Value.ToString());

                    SqlConnection myConnection = new SqlConnection(publico.ConnectionString);
                    myConnection.Open();

                    string strQuery = "UPDATE PROVIDERID SET ULTIMOID = ULTIMOID + 1 WHERE TABLA = 'TURNO';";
                    strQuery += "INSERT INTO TURNO (ID_TURNO, ID_PROF, ID_AFIL, Fecha, Estado, ID_AGENDA) VALUES ((SELECT TOP 1 ULTIMOID FROM PROVIDERID WHERE TABLA = 'TURNO'), '" + strIDProfesional + "','" + strIDAfiliado + "',CONVERT ( DATETIME, '" + dtFecha.ToString("yyyy-dd-MM HH:mm:ss") + "', 103) , 'T', '" + strIDAgendaProfesionalDelTurno + "' );";
                    strQuery = "BEGIN TRANSACTION;" + strQuery + "COMMIT TRANSACTION;";

                    SqlCommand sqlCommand = new SqlCommand(strQuery, myConnection);
                    int executeCMD = sqlCommand.ExecuteNonQuery();

                    if (executeCMD > 0)
                    {
                        Dialogos.MostrarMessageDialog("Turno Generado Satisfactoriamente para la fecha :" + dtFecha.ToString());
                        dgvElegirHorario.Rows.Clear();
                    }
                }
            }
        }
    }
}
